<template>
    <div class="bg-white p-[20px]">
        <div class="flex border-0 border-t-[1px] border-b-[1px] border-solid border-[#f2f2f2]">
            <div class="w-[140px] flex flex-col justify-between mb-[10px] mr-[10px] <lg:hidden">
                <div class="py-[20px]" v-if="!groupData.loading">
                    <div @click="changeGroup(0)"
                        class="py-6px rounded-[4px] cursor-pointer pl-[20px] my-[2px] text-sm hover:(text-[#333333] bg-[#f2f6fc])"
                        :class="[formState.group_id == 0 ? 'text-[#333333] bg-[#f2f6fc]' : '']">
                        全部
                    </div>
                    <div @click="changeGroup(item.group_id)"
                        class="py-6px rounded-[4px] cursor-pointer pl-[20px] my-[2px] text-sm hover:(text-[#333333] bg-[#f2f6fc])"
                        :class="[item.group_id == formState.group_id ? 'text-[#333333] bg-[#f2f6fc]' : '']"
                        v-for="(item, index) in groupData.data" :key="index">
                        {{ item.group_name }}
                    </div>
                </div>
                <div v-else class="py-[20px] flex items-center justify-center">
                    <a-spin />
                </div>
                <a-popconfirm ok-text="确定" :icon="false" cancel-text="取消" @confirm="addGroupconfirm">
                    <template #title>
                        <a-input v-model:value="formGroup.group_name" placeholder="请输入分组名称" show-count
                            :maxlength="10" />
                    </template>
                    <div
                        class="w-full text-center py-[5px] text-sm border-[1px] border-solid border-[#d9d9d9] rounded-[2px] ml-auto cursor-pointer">
                        添加分组
                    </div>
                </a-popconfirm>
            </div>
            <div
                class="flex-1 flex flex-col border-0 border-l-[1px] <lg:border-r-[1px] border-solid border-[#f2f2f2] px-[10px] pt-[10px]">
                <a-tabs v-model:activeKey="formGroup.type" @change="changeType">
                    <a-tab-pane :key="item.key" :tab="item.label" v-for="item in tabList"></a-tab-pane>
                </a-tabs>
                <div v-if="formGroup.type == 'image'" class="flex flex-col flex-1">
                    <div class="flex items-center justify-between mb-[10px] mx-[8px]">
                        <a-upload accept=".jpg,.png,.jpeg,.webp,.gif" list-type="picture" v-model:file-list="fileList"
                            :headers="headers" name="iFile" :data="{ group_id: formState.group_id }" :show-upload-list="false"
                            :multiple="true" :max-count="10" :action="uploadImageApi" :before-upload="beforeUpload"
                            @change="handleChange">
                            <a-button type="primary" :loading="btnLoading">上传</a-button>
                        </a-upload>

                        <a-input-search v-model:value="formState.keyword" enter-button allowClear placeholder="请输入图片名称"
                            class="w-[200px]" @search="onSearch" />
                    </div>
                    <div class="flex-1 flex flex-col justify-between" v-if="attachment.data.length > 0">
                        <div class="flex items-start flex-wrap content-start h-[530px] overflow-y-auto">
                            <div class="mb-[10px] mx-[8px]" v-for="(item, index) in attachment.data" :key="index">
                                <div
                                    class="relative w-[130px] h-[130px] flex items-center justify-center cursor-pointer bg-[#f2f6fc] rounded-[4px] overflow-hidden">
                                    <img class="w-[130px] h-[130px] object-contain" :src="imgUrl(item.url)"
                                        :alt="item.real_name">
                                </div>
                                <div
                                    class="text-sm text-[#333333] w-[130px] mt-[4px] mb-[10px] overflow-hidden overflow-ellipsis whitespace-nowrap text-center">
                                    <a-tooltip>
                                        <template #title>{{ item.real_name }}</template>
                                        {{ item.real_name }}
                                    </a-tooltip>
                                </div>
                            </div>
                        </div>
                        <div class="mt-auto py-[10px] flex justify-end">
                            <a-pagination v-model:current="formState.current_page" v-model:pageSize="formState.per_page"
                                :total="formState.total" show-less-items @change="onSearch" />
                        </div>
                    </div>
                    <div v-else class="py-[100px] h-[582px]">
                        <a-empty />
                    </div>
                </div>
                <div v-if="formGroup.type == 'video'" class="flex flex-col flex-1">
                    <div class="flex items-center justify-between mb-[10px] mx-[8px]">
                        <a-button type="primary">上传视频</a-button>
                        <a-input-search v-model:value="formState.keyword" placeholder="请输入视频名称" class="w-[200px]"
                            @search="onSearch" />
                    </div>
                    <div class="flex-1 flex flex-col justify-between" v-if="attachment.data.length > 0">
                        <div class="flex items-start flex-wrap content-start h-[530px] overflow-y-auto">
                            <div class="mb-[10px] mx-[8px]" v-for="(item, index) in attachment.data" :key="index">
                                <div
                                    class="relative flex items-center justify-center cursor-pointer bg-[#f2f6fc] rounded-[4px] overflow-hidden">
                                    <video width="320" height="240" controls>
                                        <source src="https://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4">
                                        您的浏览器不支持视频标签。
                                    </video>
                                </div>
                                <div
                                    class="text-sm text-[#333333] w-[100%] my-[10px] overflow-hidden overflow-ellipsis whitespace-nowrap text-center">
                                    <a-tooltip>
                                        <template #title>{{ item.name }}</template>
                                        {{ item.name }}
                                    </a-tooltip>
                                </div>
                            </div>
                        </div>
                        <div class="mt-auto py-[10px] flex justify-end">
                            <a-pagination v-model:current="formState.current_page" v-model:pageSize="formState.per_page"
                                :total="formState.total" show-less-items @change="onSearch" />
                        </div>
                    </div>
                    <div v-else class="py-[100px] h-[582px]">
                        <a-empty />
                    </div>
                </div>
                <div v-if="formGroup.type == 'file'" class="flex flex-col flex-1">
                    <div class="flex items-center justify-between mb-[10px] mx-[8px]">
                        <a-button type="primary">上传文件</a-button>
                        <a-input-search v-model:value="formState.keyword" placeholder="请输入文件名称" class="w-[200px]"
                            @search="onSearch" />
                    </div>
                    <div class="flex-1 flex flex-col justify-between" v-if="attachment.data.length > 0">
                        <div class="flex items-start flex-wrap content-start h-[530px] overflow-y-auto">
                            <div class="mb-[10px] mx-[8px]" v-for="(item, index) in attachment.data" :key="index">
                                <div
                                    class="relative w-[145px] h-[145px] flex items-center justify-center cursor-pointer bg-[#f2f6fc] rounded-[4px] overflow-hidden">
                                    <FileTextOutlined class="text-[100px]" />
                                </div>
                                <div
                                    class="text-sm text-[#333333] w-[145px] my-[10px] overflow-hidden overflow-ellipsis whitespace-nowrap text-center">
                                    <a-tooltip>
                                        <template #title>{{ item.name }}</template>
                                        {{ item.name }}
                                    </a-tooltip>
                                </div>
                            </div>
                        </div>
                        <div class="mt-auto py-[10px] flex justify-end">
                            <a-pagination v-model:current="formState.current_page" v-model:pageSize="formState.per_page"
                                :total="formState.total" show-less-items @change="onSearch" />
                        </div>
                    </div>
                    <div v-else class="py-[100px] h-[582px]">
                        <a-empty />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { FileTextOutlined } from '@ant-design/icons-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import useUserStore from '@/stores/user';
import { addFileGroup, fileGroupList, uploadImageApi, getFileList } from '@/utils/api/file';
import { imgUrl } from '@/utils/libs/common'

const userStore = useUserStore();

const tabList = ref([
    {
        key: 'image',
        label: '图片',
    },
    {
        key: 'video',
        label: '视频',
    },
    {
        key: 'file',
        label: '文件',
    },
]);

const changeType = (key: string) => {
    formGroup.type = key;
    //切换类型 刷新下分组
    formState.group_id = 0;
    formState.keyword = '';
    refreshGroupList();
    onSearch();
};

const changeGroup = (group_id: number) => {
    formState.group_id = group_id;
    onSearch();
};

//筛选条件
const formState = reactive({
    group_id: 0,
    keyword: '',
    current_page: 1,
    last_page: 0,
    per_page: 30,
    total: 0,
});

const attachment: Record<string, any> = reactive({
    loading: true,
    data: []
});

// 搜索框
const onSearch = () => {
    getFileList({
        group_id: formState.group_id,
        file_type: formGroup.type,
        keyword: formState.keyword,
        page: formState.current_page,
        per_page: formState.per_page
    }).then((res: any) => {
        formState.current_page = res.data.current_page;
        formState.last_page = res.data.last_page;
        formState.per_page = res.data.per_page;
        formState.total = res.data.total;
        attachment.data = res.data.data;
    })
};

//添加分组的模型
const formGroup = reactive({
    type: 'image',
    group_name: '',
    sort: 100
});

const groupData = reactive({
    data: [] as any[],
    loading: true,
});

/**
 * 确认创建分组-api请求确认创建分组
 */
const addGroupconfirm = () => {
    if (formGroup.group_name == '') {
        message.error('分组名称不能为空')
        return
    }
    addFileGroup(formGroup).then((res: any) => {
        formGroup.group_name = ''
        message.success(res.message);
        refreshGroupList();
    })
};

const initData = () => {
    refreshGroupList();
    onSearch();
};

// 刷新分组列表
const refreshGroupList = () => {
    fileGroupList({ type: formGroup.type }).then((res: any) => {
        groupData.data = res.data;
        groupData.loading = false;
    }).catch(() => {
        groupData.loading = false;
    })
}

//上传列表
const fileList = ref<UploadProps['fileList']>([]);

// 上传文件头
const headers = ref({
    Authorization: 'Bearer ' + userStore.token,
});

const btnLoading = ref(false);

const beforeUpload = (file: any) => {
    const isJpgOrPngOrWebp =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif';
    if (!isJpgOrPngOrWebp) {
        message.error('文件格式不正确!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片最大限制2MB!');
    }
    btnLoading.value = true;
    return isJpgOrPngOrWebp && isLt2M;
};

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {

        message.success(`${info.file.name} ${info.file.response.message}`);
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} ${info.file.response.message}`);
    }
    if (info.fileList.every(f => f.status === 'done')) {
        console.log('全部上传完成')
        onSearch();
    }
    btnLoading.value = false;
};

onMounted(() => {
    initData();
})
</script>